﻿package com.sshc625.core {

	/**
	 * @author sshc625
	 */
	import flash.display.DisplayObject;

	public class UIContainer extends UIObject {
		public function UIContainer() {
			super();
			construct();
		}

		/**
		 * template method for construct the children of the container
		 * this function can be overrided in the subclasses
		 */
		protected function construct():void {
			createChildren();
			layout();
		}

		/**
		 * this function must overrided in the subclass
		 * different container have the different children
		 */
		protected function createChildren():void {
			throw new Error( "Must load the resource needed" );
		}

		/**
		 * this function must overrided in the subclass
		 */
		protected function layout():void {
			throw new Error( "Must place the resource to the places they should be" );
		}

		protected function deployChild( child:DisplayObject, x:Number, y:Number ):void {
			child.x = x;
			child.y = y;
		}

		/**
		 * make the container tab key unaccessable
		 */
		public function disableTabNav():void {
			this.tabEnabled = false;
			this.tabChildren = false;
		}

		/**
		 * make the children of the container tab key unaccessable
		 * but the container tab key accessable
		 */
		public function disableChildrenTabNav():void {
			this.tabChildren = false;
		}

		/**
		 * replace the child at certain depth,not the swapDeth between the children.
		 *
		 * @see swapChildren,swapChildrenAt
		 */
		public function replaceChildAt( newChild:DisplayObject, index:uint ):void {
			if( this.numChildren < index + 1 ) {
				throw new Error( "There is no child at depth " + index );
			}
			var oldChild:DisplayObject = getChildAt( index );
			if( oldChild == newChild ) {
				return;
			}
			if( oldChild != null ) {
				removeChild( oldChild );
			}
			addChildAt( newChild, index );
		}

		/**
		 * replace the oldChild withe the newChild, not swap the two children
		 * @see swapChildren,swapChildrenAt
		 */
		public function replaceChild( newChild:DisplayObject, oldChild:DisplayObject ):void {
			var indexOfOldChild:uint = getChildIndex( oldChild );
			replaceChildAt( newChild, indexOfOldChild );
		}

		/**
		 *
		 */
		public function setChildAt( child:DisplayObject, index:Number ):void {
			if( index > this.numChildren ) {
				throw new Error( "The max depth in this container is " + this.numChildren - 1 );
			} else if( index == this.numChildren ) {
				addChildAt( child, index );
			} else {
				replaceChildAt( child, index );
			}
		}

		/**
		 * remove all the children in a UIContainer
		 */
		public function removeChildren():void {
			while( this.numChildren > 0 ) {
				removeChildAt( 0 );
			}
		}

	}
}